package com.wmx;

import com.wmx.dto.RestfulResultDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 
 * 自定义的异常处理器
 * <p>
 * 如在开发过程中针对指定异常有特定需求,还可以在此类中进行扩展.如编写独立的方法.
 * 
 */
@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public RestfulResultDto handle(Exception exception) {

		String errorMessage = "亲,服务器开小差了...";
		RestfulResultDto restfulResultDto = new RestfulResultDto("500", errorMessage);

	  if (exception instanceof IllegalArgumentException) {
			errorMessage = exception.getMessage();
			log.error("非法参数异常: {}", errorMessage, exception);
			
		} else if (exception instanceof BindException) {
			// 普通对象参数校验
			BindingResult result = (BindingResult) exception;
			errorMessage = result.getAllErrors().get(0).getDefaultMessage();
			log.error("参数绑定失败: {}", errorMessage);
			
		} else if (exception instanceof MethodArgumentNotValidException) {
			// 复杂对象参数嵌套校验
			MethodArgumentNotValidException ex = (MethodArgumentNotValidException) exception;
			errorMessage = ex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
			log.error("参数绑定失败: {}", errorMessage);
			
		} else if (exception instanceof ConstraintViolationException) {
			// 简单参数直接校验
			ConstraintViolationException ex = (ConstraintViolationException) exception;
			errorMessage = ex.getConstraintViolations().iterator().next().getMessage();
			log.error("参数绑定失败: {}", errorMessage);
			
		} else {
			log.error("未知异常: {}", exception);
		}
		
		restfulResultDto.setMessage(errorMessage);
//		log.error("异常堆栈: {}", exception);
		return restfulResultDto;
	}
	
}
